package temp.lho.lws.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import temp.lho.lws.pojo.DataUploadInfo;
import temp.lho.lws.result.ResultBody;
import temp.lho.lws.service.IDataUploadInfoService;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * (DataUploadInfo)表控制层
 *
 * @author makejava
 * @since 2020-07-06 23:08:54
 */
@RestController
@RequestMapping("/dataUploadInfo")
public class DataUploadInfoController {

    @Autowired
    private IDataUploadInfoService dataUploadInfoService;

    @PostMapping("/uploadImg")
    public ResultBody upload(MultipartFile file, Integer claimmainid ,String dataname ,HttpServletRequest request)
            throws IllegalStateException, IOException {

        // 判断文件是否为空，空则返回失败页面
        if (file.isEmpty()) {
            return ResultBody.toResultBody(-1,"上传失败！");
        }
        //获取文件后缀名
        String filename = file.getOriginalFilename();
        String fileSuffix = filename.substring(filename.lastIndexOf('.'));
        // 获取文件存储路径（绝对路径）
        String path = request.getServletContext().getRealPath("/static/upload");
        // 创建文件实例
        File filePath = new File(path, dataname + claimmainid + fileSuffix);

        // 如果文件目录不存在，创建目录
        if (!filePath.getParentFile().exists()) {
            filePath.getParentFile().mkdirs();
        }
        // 写入文件
        file.transferTo(filePath);

        //添加资料表信息
        DataUploadInfo dataUploadInfo = new DataUploadInfo();
        dataUploadInfo.setClaimmainid(claimmainid);
        dataUploadInfo.setDataname(dataname);
        dataUploadInfo.setDataurl(filePath.getName());

        int add = dataUploadInfoService.add(dataUploadInfo);

        return add > 0 ? ResultBody.toResultBody(200,"上传成功！"): ResultBody.toResultBody(-1,"上传失败！");
    }

    @GetMapping("/findUploadInit")
    public ResultBody findUploadInit(Integer claimmainid) {
        List<DataUploadInfo> uploadInit = dataUploadInfoService.findUploadInit(claimmainid);
        return uploadInit.size() == 0 ? ResultBody.toResultBody(-1,"") : ResultBody.toResultBody(200,"" ,uploadInit);
    }

}